package m2;

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接消息服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);//默认的端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c=f.newConnection().createChannel();//连接

        //定义队列
        c.queueDeclare("task_queue", false, false, false, null);
        //回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {//回调对象
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {//Delivery消息的封装对象用来封装对象
                String msg = new String(message.getBody());
                System.out.println("收到："+msg);
                //遍历消息字符的所有字符，每个字符都能暂停一秒，模拟好事消息
                for (int i=0;i<msg.length();i++){
                    if (msg.charAt(i)=='.'){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                     }
                    }
                }
                //手动发送回执
                //参数1.回执数据 2.是否同时确认多条消息
                c.basicAck(message.getEnvelope().getDeliveryTag(), false );
                System.out.println("----------消息处理结束");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //每次只抓取一条数据，这条数据处理完成之前不抓取下一条
        c.basicQos(1);

        //消费数据
        //第二个参数时 ack 模式
        //false-手动确认
        //true-自动确认
        c.basicConsume("task_queue", false,deliverCallback,cancelCallback);
    }
}
